package org.enhance.local.tq.factory.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.enhance.local.tq.annotation.TqHandler;
import org.enhance.local.tq.factory.TaskQueueClientFactory;
import org.enhance.local.tq.task.ITqHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TaskQueueSpringClientFactory implements ApplicationContextAware, DisposableBean {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        List<ITqHandler> handlerList = new ArrayList<>();
        Map<String, Object> serviceMap = applicationContext.getBeansWithAnnotation(TqHandler.class);
        if (serviceMap!=null && serviceMap.size()>0) {
            for (Object serviceBean : serviceMap.values()) {
                if (serviceBean instanceof ITqHandler) {
                    handlerList.add((ITqHandler) serviceBean);
                }
            }
        }

        boolean tqEnable = Boolean.parseBoolean(applicationContext.getEnvironment().getProperty("tq.enable"));

        // init
        if(CollectionUtils.isNotEmpty(handlerList) && tqEnable) {
            TaskQueueClientFactory.getInstance().setHandler(handlerList);
            TaskQueueClientFactory.getInstance().init();
        }
    }

    @Override
    public void destroy() throws Exception {
        TaskQueueClientFactory.getInstance().destroy();
    }

}
